<?php

namespace ASW\Utility\Logging\Providers;

use ASW\Utility\Folder;
use ASW\Utility\Logging\ILogProvider;
use ASW\Utility\Logging\LogLevel;
use Throwable;

class FileLogProvider implements ILogProvider
{
    public function __construct(private readonly LogLevel $minLevel = LogLevel::DEBUG, private readonly string $baseDir = './log')
    {

    }

    public function log(LogLevel $logLevel, string $category, string $message, Throwable $throwable = null): void
    {
        if ($logLevel->value < $this->minLevel->value) return;
        Folder::create($this->baseDir);

        $fileNameDatePart = date('Ymd');
        $categoryPart     = empty($category) ? "" : str_replace(['/', '\\', ':', '*', '?', '"', '\'', '<', '>', '|', ' '], '_', $category) . '_';
        $fileName         = "$categoryPart$fileNameDatePart.log";
        $fileFullName     = "$this->baseDir/$fileName";

        $timePart      = date('H:i:s');
        $levelPart     = str_pad($logLevel->name, 6);
        $throwablePart = empty($throwable) ? '' : "\r\nthrow: \r\n" . $throwable->getTraceAsString();
        $logContent    = "$timePart | $levelPart | $message$throwablePart\r\n";

        file_put_contents($fileFullName, $logContent, FILE_APPEND);
    }
}